package com.jxbeidou.system.menu.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import com.jxbeidou.core.entity.PageResult;
import com.jxbeidou.core.mybatis.service.impl.BaseServiceImpl;
import com.jxbeidou.core.mybatis.convert.PageResultConvert;
import com.jxbeidou.system.menu.convert.RoleConvert;
import com.jxbeidou.system.menu.entity.RoleDO;
import com.jxbeidou.system.menu.query.RoleQuery;
import com.jxbeidou.system.menu.vo.RoleVO;
import com.jxbeidou.system.menu.mapper.RoleMapper;
import com.jxbeidou.system.menu.service.RoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 角色表
 *
 * @author 杜晓祥 
 * @since 1.0.0 2023-12-14
 */
@Service
@AllArgsConstructor
public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, RoleDO> implements RoleService {

    @Override
    public PageResult<RoleVO> page(RoleQuery query) {
        IPage<RoleDO> page = baseMapper.selectPage(getPage(query), getWrapper(query));
        PageResult<RoleVO> result = PageResultConvert.convert(page, entityList -> RoleConvert.INSTANCE.convertList(entityList));
        return result;
    }

    private LambdaQueryWrapper<RoleDO> getWrapper(RoleQuery query){
        LambdaQueryWrapper<RoleDO> wrapper = Wrappers.lambdaQuery();
        wrapper.like(StringUtils.isNotEmpty(query.getName()), RoleDO::getName, query.getName());
        wrapper.eq(query.getStatus() != null, RoleDO::getStatus, query.getStatus());
        return wrapper;
    }

    @Override
    public void save(RoleVO vo) {
        RoleDO entity = RoleConvert.INSTANCE.convert(vo);

        baseMapper.insert(entity);
    }

    @Override
    public void update(RoleVO vo) {
        RoleDO entity = RoleConvert.INSTANCE.convert(vo);

        updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> idList) {
        removeByIds(idList);
    }

}